<?php
namespace Src;

use Swoole\Coroutine;
//当request函数外，有全局变量要引入到协程使用时，必须使用此种方法来隔离全局变量，
//协程退出时候清理，$response->end(Context::get('name'));Context::delete('name');
//Context::put('name', 'a');Context::get('name')
class Context
{
    protected static $pool = [];

    static function get($key)
    {
        $cid = Coroutine::getcid();
        if ($cid < 0)
        {
            return null;
        }
        if(isset(self::$pool[$cid][$key])){
            return self::$pool[$cid][$key];
        }
        return null;
    }

    static function set($key, $item)
    {
        $cid = Coroutine::getcid();
        if ($cid > 0)
        {
            self::$pool[$cid][$key] = $item;
        }
    }

    static function show()
    {
        echo 'show'.PHP_EOL;
        $cid = Coroutine::getcid();
        if ($cid > 0)
        {
            var_dump(self::$pool);
        }
    }

    static function delete($key = null)
    {
        $cid = Coroutine::getcid();
        if ($cid > 0)
        {
            if($key){
                echo 1;
                unset(self::$pool[$cid][$key]);
            }else{
                unset(self::$pool[$cid]);
            }
        }
    }
}

